<template>
  <el-drawer
    :visible.sync="visible"
    :title="title"
    :size="'80%'"
    :wrapper-closable="false"
    class="drawer"
  >
    <!-- 支付接口列表 -->
    <el-table :data="payConfigList" style="width: 100%">
      <el-table-column label="支付接口" align="center">
        <template slot-scope="scope">
          <div>
            <span>{{ scope.row.ifName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="ifConfigState" label="状态" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.ext.fConfigState === 1 ? 'success' : 'info'" size="small">
            {{ scope.row.ext.ifConfigState === 1 ? '已启用' : '未开通' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="editPayIfConfigFunc(scope.row)"
          >
            填写参数<i class="el-icon-right"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 参数配置抽屉 -->
    <el-drawer
      :visible.sync="innerVisible"
      :title="innerTitle"
      :size="'40%'"
      :wrapper-closable="false"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="支付接口费率" prop="ifRate">
          <el-input-number
            v-model="form.ifRate"
            :precision="4"
            :step="0.1"
            :max="100"
          >
            <template slot="append">%</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="form.remark"/>
        </el-form-item>

        <!-- 动态参数配置 -->
        <el-divider content-position="left">
          <el-tag type="danger">{{ form.ifCode }} 服务商参数配置</el-tag>
        </el-divider>

        <el-form ref="paramForm" :model="ifParams" :rules="paramRules">
          <el-form-item
            v-for="item in isvParams"
            :key="item.name"
            :label="item.desc"
            :prop="item.name"
          >
            <el-input
              v-if="item.type === 'text' || item.type === 'textarea'"
              v-model="ifParams[item.name]"
              :type="item.type"
              :placeholder="item.star === '1' ? ifParams[item.name + '_ph'] : '请输入'"
            />

            <el-radio-group
              v-else-if="item.type === 'radio'"
              v-model="ifParams[item.name]"
            >
              <el-radio
                v-for="opt in item.values"
                :key="opt.value"
                :label="opt.value"
              >{{ opt.title }}</el-radio>
            </el-radio-group>

            <template v-else-if="item.type === 'file'">
              <el-input v-model="ifParams[item.name]" disabled />
              <file-upload
                v-model="ifParams[item.name]"
                :limit="1"
                :fileSize="2"
                :fileType="['p12', 'pem', 'crt']"
                @success="(response) => handleUploadSuccess(response, item.name)"
              />
            </template>
          </el-form-item>
        </el-form>
      </el-form>

      <div class="drawer-footer">
        <el-button @click="innerVisible = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="onSubmit">确 定</el-button>
      </div>
    </el-drawer>

  <!-- 支付参数配置页面组件  -->
  <WxpayPayConfig ref="wxpayPayConfig" :callbackFunc="refCardList" />
    <!-- 支付参数配置页面组件  -->
    <AlipayPayConfig ref="alipayPayConfig" :callbackFunc="refCardList" />
  </el-drawer>
</template>

<script>
import { getIsvPayConfigUnique, getPayList} from '@/api/pay/isv/IsvPayIfConfigList'
import WxpayPayConfig from './custom/WxpayPayConfig'
import AlipayPayConfig from './custom/AlipayPayConfig'
import ImagePreview from '@/components/ImagePreview'

export default {
  name: 'IsvPayConfig',
  components: {
    WxpayPayConfig,
    AlipayPayConfig,
    ImagePreview
  },
  data() {
    return {
      // 显示状态
      visible: false,
      innerVisible: false,
      loading: false,

      // 标题
      title: '支付参数配置',
      innerTitle: '编辑支付参数',

      // 数据对象
      isvNo: null,
      payConfigList: [],
      form: {},
      ifParams: {},
      isvParams: [],

      // 上传地址
      uploadUrl: process.env.VUE_APP_BASE_API + '/common/upload',

      // 表单校验
      rules: {
        ifRate: [
          { required: false, pattern: /^(([1-9]{1}\d{0,1})|(0{1}))(\.\d{1,4})?$/, message: '请输入0-100之间的数字，最多四位小数' }
        ]
      },
      paramRules: {}
    }
  },
  created() {
    this.refCardList()
  },
  watch: {
    ifParams: function (o, n) {
      this.$set(this.ifParams, 'appSecret', this.ifParams.appSecret) // 解决appSecret  双向绑定数据不显示的问题
    }
  },
  methods: {
    generoterRules () {
      const rules = {}
      let newItems = []
      this.isvParams.forEach(item => {
        newItems = []
        if (item.verify === 'required' && item.star !== '1') {
          newItems.push({
            required: true,
            message: '请输入' + item.desc,
            trigger: 'blur'
          })
          rules[item.name] = newItems
        }
      })
      this.ifParamsRules = rules
    },
    show(userId) {
      this.isvNo = userId
      this.visible = true
      this.refCardList()
    },
     /** 获取支付配置列表 */
     refCardList() {
      if (!this.isvNo) return
      getPayList(this.isvNo).then(response => {
        this.payConfigList = response.data
      })
    },
    /** 编辑按钮操作 */
   // 支付参数配置
   editPayIfConfigFunc (record) {
      if (record.configPageType === 1) { // JSON渲染页面
        if (this.$refs.infoFormModel !== undefined) {
          this.$refs.infoFormModel.resetFields()
        }
        if (this.$refs.isvParamFormModel !== undefined) {
          this.$refs.isvParamFormModel.resetFields()
        }
        this.childrenVisible = true // 打开支付参数配置抽屉
        this.saveObject = {} // 要保存的对象
        this.ifParams = {} // 参数配置对象
        this.isvParams = {} // 支付接口定义描述
        this.saveObject.infoId = this.isvNo
        this.saveObject.ifCode = record.ifCode
        this.saveObject.state = record.ifConfigState === 0 ? 0 : 1

        if (!record) {
          return
        }

        const that = this
        // 获取支付参数
        getIsvPayConfigUnique(this.saveObject.infoId, this.saveObject.ifCode).then(res => {
          if (res && res.ifParams) {
            this.saveObject = res
            this.ifParams = JSON.parse(res.ifParams)
          }

          const newItems = [] // 重新加载支付接口配置定义描述json
          JSON.parse(record.isvParams).forEach(item => {
            const radioItems = [] // 存放单选框value title
            if (item.type === 'radio') {
              const valueItems = item.values.split(',')
              const titleItems = item.titles.split(',')

              for (const i in valueItems) {
                // 检查参数是否为数字类型 然后赋值给radio值
              let radioVal = valueItems[i]
              if (!isNaN((radioVal))) { radioVal = Number(radioVal) }

                radioItems.push({
                  value: radioVal,
                  title: titleItems[i]
                })
              }
            }

            if (item.star === '1') {
              that.ifParams[item.name + '_ph'] = that.ifParams[item.name] ? that.ifParams[item.name] : '请输入'
              if (that.ifParams[item.name]) {
                that.ifParams[item.name] = ''
              }
            }

            newItems.push({
              name: item.name,
              desc: item.desc,
              type: item.type,
              verify: item.verify,
              values: radioItems,
              star: item.star // 脱敏标识 1-是
            })
          })
          that.isvParams = newItems // 重新赋值接口定义描述
          that.generoterRules()
          that.$forceUpdate()
        })
      } else if (record.configPageType === 2) { // 自定义配置页面，页面放在custom目录下，配置模块命名规则：if_code + PayConfig
        this.$refs[record.ifCode + 'PayConfig'].show(this.isvNo, record)
      }
    },
    // 表单提交
    onSubmit () {
      const that = this
      this.$refs.infoFormModel.validate(valid => {
        this.$refs.isvParamFormModel.validate(valid2 => {
          if (valid && valid2) { // 验证通过
            that.btnLoading = true
            const reqParams = {}
            reqParams.infoId = that.saveObject.infoId
            reqParams.ifCode = that.saveObject.ifCode
            reqParams.ifRate = that.saveObject.ifRate
            reqParams.state = that.saveObject.state
            reqParams.remark = that.saveObject.remark
            // 支付参数配置不能为空
            if (Object.keys(that.ifParams).length === 0) {
              this.$message.error('参数不能为空！')
              return
            }
            // 脱敏数据为空时，删除该key
            this.isvParams.forEach(item => {
              if (item.star === '1' && that.ifParams[item.name] === '') {
                that.ifParams[item.name] = undefined
              }
              that.ifParams[item.name + '_ph'] = undefined
            })
            reqParams.ifParams = JSON.stringify(that.ifParams)
            // 请求接口
            req.add(API_URL_ISV_PAYCONFIGS_LIST, reqParams).then(res => {
              that.$message.success('保存成功')
              that.childrenVisible = false
              that.refCardList()
              that.btnLoading = false
            })
          }
        })
      })
    },
    handleUploadSuccess(response, name) {
      this.ifParams[name] = response.url
      this.$forceUpdate()
    },
    reset() {
      if (this.$refs.form) {
        this.$refs.form.resetFields()
      }
      if (this.$refs.paramForm) {
        this.$refs.paramForm.resetFields()
      }
      this.form = {}
      this.ifParams = {}
    },
    onClose() {
      this.innerVisible = false
    },
     /** 图片预览 */
     handlePreview(file) {
      this.previewImage = file.url;
      this.previewVisible = true;
    },
  }
}
</script>

<style lang="scss" scoped>
.drawer {
  ::v-deep .el-drawer__body {
    padding: 20px;
  }
}
</style>
